package com.hex.es.service.impl;

import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.aop.AbstractEsAop;
import com.hex.es.service.ParamBuildInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

/**
 * @description: 分页参数构建器
 * @author: Hex
 * @date: 2019/11/20 16:29
 */
@Slf4j
@Service
public class ParamBuildPageImpl extends AbstractEsAop implements ParamBuildInterface {

    private static final String PAGE_PARAM = "page_param";

    @Override
    public void paramBuild(Object key, Object value, BoolQueryBuilder boolQueryBuilder, NativeSearchQueryBuilder searchQueryBuilder, EsBuildParamTypeInfo esBuildParamTypeInfo) {
        //默认查询0到1000条
        searchQueryBuilder.withPageable(PageRequest.of(0, 1000));
        if (value != null && StringUtils.isNotEmpty(value.toString())) {
            if (key.equals(esBuildParamTypeInfo.rowOffsetFieldName())) {
                int start = (int) value;
                if (PARAM_THREAD_LOCAL.get().get(PAGE_PARAM) == null) {
                    PARAM_THREAD_LOCAL.get().put(PAGE_PARAM, start);
                } else {
                    searchQueryBuilder.withPageable(PageRequest.of(start, (Integer) PARAM_THREAD_LOCAL.get().get(PAGE_PARAM)));
                }
            }
            if (key.equals(esBuildParamTypeInfo.pageSizeFieldName())) {
                int size = (int) value;
                if (PARAM_THREAD_LOCAL.get().get(PAGE_PARAM) == null) {
                    PARAM_THREAD_LOCAL.get().put(PAGE_PARAM, size);
                } else {
                    searchQueryBuilder.withPageable(PageRequest.of((Integer) PARAM_THREAD_LOCAL.get().get(PAGE_PARAM), size));
                }
            }
        }
    }
}
